console.log('Background script loaded');

API_KEY = '';

// 读取prompt.txt中的分类提示词
let prompts = '';
let promptsLoaded = false;

fetch(chrome.runtime.getURL('prompt.txt'))
  .then(response => response.text())
  .then(text => {
    prompts = text;
    promptsLoaded = true;
    // console.log('提示词加载完成');
  })
  .catch(error => {
    console.error('读取提示词失败:', error);
    prompts = '默认提示词: 请总结这个工单对话';
    promptsLoaded = true;
  });


// 监听content.js的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'summarize') {
    if (!promptsLoaded) {
      sendResponse({error: '提示词正在加载，请稍后再试'});
      return true;
    }

    const conversation = request.data;
    console.log('收到对话内容:', conversation);
    
    // 构造API请求数据
    const apiRequest = {
      model: "deepseek-chat",
      messages: [
        {
          role: "system",
          content: prompts
        },
        {
          role: "user",
          content: `请根据以下对话内容进行分类和总结：\n\n${
            conversation.map(msg => `${msg.role}: ${msg.content}`).join('\n')
          }`
        }
      ]
    };

    // 调用deepseek API
    fetch('https://api.deepseek.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify(apiRequest)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      if (!data.choices || !data.choices[0]) {
        throw new Error('无效的API响应格式');
      }

      const summary = data.choices[0].message.content;

      console.log(summary);  // .slice(8, -4)

      const summary_obj = JSON.parse(summary);

      // 发送回content.js
      chrome.tabs.sendMessage(sender.tab.id, {
        action: 'fill',
        category_id: summary_obj.category_id,
        category_name: summary_obj.category_name,
        description: summary_obj.description,
      });
    })
    .catch(error => {
      console.error('处理失败:', error);
      chrome.tabs.sendMessage(sender.tab.id, {
        action: 'apiError',
        message: error.message
      });
    });
  }
});
